package com.mzy.linear_struct.ks.链表;

/**
 * @Author: mizy3
 * @Date: 2024/08/07/下午1:41
 * @Description:
 */
public class Pro148排序链表 {

    public static ListNode sortList(ListNode head) {
        if (head == null || head.next == null) return null;

        ListNode slow = head;
        ListNode fast = head;
        fast = fast.next;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        // 找到中点的前一个元素，slow就是
        // 切断
        ListNode temp = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(temp);

        ListNode dummy = new ListNode(0);
        ListNode ans = dummy;
        while (left != null && right != null) {
            if (left.val < right.val) {
                dummy.next = left;
                left = left.next;
            } else {
                dummy.next = right;
                right = right.next;
            }
            dummy = dummy.next;
        }

        while (left != null) {
            dummy.next = left;
            dummy = dummy.next;
            left = left.next;
        }

        while (right != null) {
            dummy.next = right;
            dummy = dummy.next;
            right = right.next;

        }
        return ans.next;
    }
}
























